<template>
  <editor-content class="tiptap" :editor="editor as Editor" />
</template>

<script setup lang="ts">
import { Editor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import { watch, onBeforeUnmount, nextTick, onMounted, ref } from 'vue'
import Mention from '@tiptap/extension-mention'
import suggestion from '../MentionList/suggestion.ts'
import Text from '@tiptap/extension-text'
import Document from '@tiptap/extension-document'
import Bold from '@tiptap/extension-bold'
import Paragraph from '@tiptap/extension-paragraph'
import type { Editor as EditorType } from '@tiptap/vue-3'

// 自定义 Bold 扩展，使用 <b> 标签而不是 <strong>
const CustomBold = Bold.extend({
  renderHTML({ HTMLAttributes }: { HTMLAttributes: Record<string, any> }) {
    return ['b', HTMLAttributes, 0]
  },
})

// 自定义段落扩展，使用 span 而不是 p 标签
const CustomParagraph = Paragraph.extend({
  addAttributes() {
    return {
      class: {
        default: 'custom-span',
        parseHTML: element => element.getAttribute('class'),
        renderHTML: attributes => {
          return {
            class: attributes.class,
          }
        },
      },
      style: {
        default: null,
        parseHTML: element => element.getAttribute('style'),
        renderHTML: attributes => {
          return {
            style: attributes.style,
          }
        },
      },
    }
  },
  
  renderHTML({ HTMLAttributes }: { HTMLAttributes: Record<string, any> }) {
    return ['span', HTMLAttributes, 0]
  },
})

const props = defineProps<{
  modelValue: string
  at?: {
    list: Array<{ id: string; name: string }>
  }
}>()

const emit = defineEmits<{
  'update:modelValue': [value: string]
}>()

const editor = ref<EditorType | null>(null)

onMounted(() => {
  if (editor.value) return
  
  // 创建扩展数组
  const extensions = [
    Document,
    StarterKit.configure({
      // 使用自定义段落扩展
      paragraph: false,
    }),
    CustomParagraph,
    Text,
    CustomBold,
  ]
  
  // 只有当 at.list 有数据时才添加 Mention 扩展
  if (props?.at?.list?.length) {
    // 创建自定义的 suggestion 配置
    const customSuggestion = {
      ...suggestion,
      items: ({ query }: { query: string; editor: any }) => {
        if (!props.at?.list) {
          return []
        }
        
        return props.at.list
          .filter(item => item.name.toLowerCase().includes(query.toLowerCase()))
          .map(item => ({ id: item.id, name: item.name }))
      }
    }
    
    extensions.push(
      Mention.configure({
        suggestion: customSuggestion,
        renderHTML({ node, HTMLAttributes }: { node: any; HTMLAttributes: any }) {
          // 获取当前选中的项目数据
          const selectedItem = props.at?.list?.find(item => item.id === node.attrs.id)
          const userData = selectedItem ? JSON.stringify(selectedItem) : '{}'
          
          return [
            'span',
            {
              ...HTMLAttributes,
              'data-user': userData,
              'data-type': 'mention',
              'data-id': node.attrs.id,
              'data-mention-suggestion-char': '@',
              contenteditable: 'false',
              'class':'rich-mention'
            },
            `@${selectedItem?.name || node.attrs.id}`
          ]
        }
      })
    )
  }
  
  editor.value = new Editor({
    content: props.modelValue,
    extensions,
    editable: true,
    onUpdate: ({ editor }) => {
      const html = editor.getHTML()
      // 避免无限循环，只有当内容真正改变时才触发更新
      if (html !== props.modelValue) {
        emit('update:modelValue', html)
      }
    }
  })
})

// 监听外部modelValue的变化，同步到编辑器
watch(() => props.modelValue, (newValue, oldValue) => {
  if (editor.value && newValue !== oldValue) {
    const currentContent = editor.value.getHTML()
    // 只有当内容真正不同时才更新
    if (currentContent !== newValue) {
      editor.value.commands.setContent(newValue, {
        emitUpdate: false
      })
    }
  }
}, { immediate: true })

// 监听 at.list 的变化，重新创建编辑器
watch(() => props.at?.list, (newValue, oldValue) => {
  if (newValue !== oldValue && editor.value) {
    // 保存当前内容
    const currentContent = editor.value.getHTML()
    
    // 销毁当前编辑器
    editor.value.destroy()
    editor.value = null
    
    // 重新创建编辑器
    nextTick(() => {
      if (editor.value) return
      
      // 创建扩展数组
      const extensions = [
        Document,
        StarterKit.configure({
          // 使用自定义段落扩展
          paragraph: false,
        }),
        CustomParagraph,
        Text,
        CustomBold,
      ]
      
      // 只有当 at.list 有数据时才添加 Mention 扩展
      if (props.at?.list && props.at.list.length > 0) {
        // 创建自定义的 suggestion 配置
        const customSuggestion = {
          ...suggestion,
          items: ({ query }: { query: string; editor: any }) => {
            if (!props.at?.list) {
              return []
            }
            
            return props.at.list
              .filter(item => item.name.toLowerCase().includes(query.toLowerCase()))
          }
        }
        
        extensions.push(
          Mention.configure({
            HTMLAttributes: {
              class: 'rich-mention',
            },
            suggestion: customSuggestion,
            renderHTML({ node, HTMLAttributes }: { node: any; HTMLAttributes: any }) {
              // 获取当前选中的项目数据
              const selectedItem = props.at?.list?.find(item => item.id === node.attrs.id)
              const userData = selectedItem ? JSON.stringify(selectedItem) : '{}'
              
              return [
                'span',
                {
                  ...HTMLAttributes,
                  'data-user': userData,
                  'data-type': 'mention',
                  'data-id': node.attrs.id,
                  'data-mention-suggestion-char': '@',
                  contenteditable: 'false'
                },
                `@${selectedItem?.name || node.attrs.id}`
              ]
            }
          })
        )
      }
      
      editor.value = new Editor({
        content: currentContent,
        extensions,
        editable: true,
        onUpdate: ({ editor }) => {
          const html = editor.getHTML()
          // 避免无限循环，只有当内容真正改变时才触发更新
          if (html !== props.modelValue) {
            emit('update:modelValue', html)
          }
        }
      })
    })
  }
})

// 组件销毁时清理编辑器实例
onBeforeUnmount(() => {
  if (editor.value) {
    editor.value.destroy()
  }
})
</script>
<style lang="scss" scoped>
.tiptap {
  width: 100%;
  height: 100%;
  border: 1px solid red;
  border-radius: 8px;
  padding: 10px;
  overflow-y: auto;

  :deep(.ProseMirror) {
    height: 100%;
    min-height: 150px;
    outline: none !important;
    border: none !important;
    font-size: 16px;
  }

  // 去掉聚焦时的所有边框和轮廓
  :deep(.ProseMirror-focused) {
    outline: none !important;
    border: none !important;
    box-shadow: none !important;
  }

  // 去掉所有可能的聚焦样式
  :deep(.ProseMirror:focus) {
    outline: none !important;
    border: none !important;
    box-shadow: none !important;
  }

  // 去掉编辑器容器的聚焦样式
  &:focus {
    outline: none !important;
    border: 1px solid red !important;
    box-shadow: none !important;
  }

  // 去掉所有子元素的聚焦样式
  :deep(*) {
    &:focus {
      outline: none !important;
      box-shadow: none !important;
    }
  }

  // 确保 mention 样式在编辑器内正确显示
  :deep(.rich-mention) {
    border-radius: 4px !important;
    box-decoration-break: clone !important;
    color: #6a00f5 !important;
    padding: 2px 4px !important;
    font-weight: bold !important;
  }

  // 自定义 span 标签样式
  :deep(span) {
  }

  // 针对段落 span 的特定样式
  :deep(.ProseMirror > span) {
    display: block;
    // 添加你想要的样式
  }

  // 针对自定义段落类的样式
  :deep(.custom-span) {
    display: block;
    color: #333;
    font-size: 16px;
    // 你可以添加更多样式
    // background-color: #f5f5f5;
    // padding: 10px;
    // border-left: 3px solid #007bff;
  }
}
</style>
